package java学习.第10章_多线程的入门;

public class G_线程间的通信 {
    public static int food = 0;
    public static void main(String[] args) {
        交替打印();
    }

    private static void 交替打印() {
        G g = new G();
        new Thread(g).start();
        new Thread(g).start();
        new Thread(g).start();
    }
}
class G implements Runnable{

    private int a = 0;
    @Override
    public void run() {
        while (true){
            //wait()   notify()  只能在synchronized内使用,且调用者和synchronized内的一致
            synchronized (this){
                notify();//唤醒一个 被wait()的方法
//                notifyAll();//唤醒所有
                if(a<100){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() +
                            ":" + a++);
                    try {
                        wait();//等待，同时释放被锁的调用,等待被唤醒
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }else {
                    break;
                }
            }
        }
    }
}